<template>
  <view>
    <form @submit.prevent="submitData" class="form-view">
      <view class="form-item">
        <view class="form-up">
          <view class="form-label">
            商铺LOGO（仅可上传一张）
            <text class="icon-requird">*</text>
          </view>
          <view class="form-value clearfix">
            <image
              v-if="form.logo"
              class="cata-img float_left"
              :src="form.logo"
              mode="aspectFill"
            ></image>
            <QiniuUpload
              :count="1"
              @uploadSuccess="uploadSuccess"
              class="float_left"
            >
              <view slot="cont" class="upload-view"
                ><i class="ibonfont ibonxinzeng"></i
              ></view>
            </QiniuUpload>
          </view>
        </view>
      </view>
      <view class="form-item b20 clearfix">
        <view class="form-label">商铺编码</view>
        <view class="float_right form-value">
          <text class="input-pl" v-if="!form.shopCode">系统自动生成</text>
          <text v-else>{{ form.shopCode }}</text>
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">商铺名称</view>
        <view class="float_right form-value"
          ><input
            placeholder="请输入名称"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.name"
            name="name"
        /></view>
      </view>
      <view class="form-item">
        <view class="form-up">
          <view class="form-label clearfix">
            <text class="float_left">仓库</text>
            <i class="ibonfont ibonjinru icon-jinru float_right"></i>
          </view>
          <view class="form-value clearix">
            <view
              v-for="(item, index) in warehouse_arr"
              :key="index"
              class="tag-item"
              style="
                display: inline-block;
                background: #f0f0f0;
                padding: 2px 8px;
                border-radius: 4px;
                margin-right: 6px;
              "
            >
              {{ item.warehouseName }}
              <button
                size="mini"
                type="warn"
                @click="delWarehouse(index)"
                style="margin-left: 4px"
              >
                删除
              </button>
            </view>
            <button
              size="mini"
              type="primary"
              class="tag-item"
              @click="chooseWarehouse"
            >
              <i class="ibonfont ibonxinzeng"></i>
              <text>选择</text>
            </button>
          </view>
        </view>
      </view>
      <view class="form-item b20 clearfix">
        <view class="form-label">商铺类型</view>
        <view class="float_right form-value">
          <picker
            :range="shopTypeList"
            range-key="label"
            @change="shopChangePicker"
          >
            <text class="sel-label sel-name" v-if="shopTypeName">{{
              shopTypeName
            }}</text>
            <text class="input-pl" v-else>请选择</text>
            <i class="ibonfont ibonjinru icon-jinru"></i>
          </picker>
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">商铺地址</view>
        <view class="float_right form-value" @click="regionOpen">
          <text v-if="regionName">{{ regionName }}</text>
          <text class="input-pl" v-else>请选择所属区域</text>
          <RegionSel
            v-model="region_show"
            @confirm="regionConfirm"
            @cancel="regionCancel"
          ></RegionSel>
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </view>
      <view class="form-item">
        <view class="form-up">
          <view class="form-label">
            营业时间
            <text class="icon-requird">*</text>
          </view>
          <view class="form-value clearfix">
            <view class="float_left form-value" @click="showTime = true">
              <picker
                mode="time"
                start="8:00"
                end="24:00"
                @change="startTimeChange"
                :disabled="form.openTime.isAllDay === 1"
                ref="endtime"
              >
                <view
                  class="TimeBorder"
                  :class="[form.openTime.isAllDay === 1 ? 'dis-time' : '']"
                  v-if="form.openTime.start"
                  >{{ form.openTime.start }}</view
                >
                <view
                  class="input-pl TimeBorder"
                  :class="[form.openTime.isAllDay === 1 ? 'dis-time' : '']"
                  v-else
                  >开始时间</view
                >
              </picker>
            </view>
            <view class="float_left line">-</view>
            <view class="float_left form-value">
              <picker
                :disabled="form.openTime.isAllDay === 1"
                mode="time"
                start="8:00"
                end="24:00"
                @change="endTimeChange"
                ref="endtime"
              >
                <view
                  class="TimeBorder"
                  :class="[form.openTime.isAllDay === 1 ? 'dis-time' : '']"
                  v-if="form.openTime.end"
                  >{{ form.openTime.end }}</view
                >
                <view
                  class="input-pl TimeBorder"
                  :class="[form.openTime.isAllDay === 1 ? 'dis-time' : '']"
                  v-else
                  >结束时间</view
                >
              </picker>
            </view>
          </view>
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">是否全天</view>
        <view class="float_right form-value dataAu-ul">
          <view class="float_right form-value"
            ><switch
              :checked="form.openTime.isAllDay === 1"
              @change="switchChange"
          /></view>
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">详细地址</view>
        <view class="form-value" @click="chooseLocation">
          <text class="input-pl" v-if="!form.address">请选择</text>
          <text v-else>{{ form.address }}</text>
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">联系人</view>
        <view class="float_right form-value">
          <input
            type="text"
            placeholder="请输入客户联系人"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.contactName"
            name="contactName"
          />
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">联系电话</view>
        <view class="float_right form-value">
          <input
            type="text"
            placeholder="请输入客户联系人电话"
            placeholder-class="input-pl"
            class="form-input"
            v-model="form.mobile"
            name="mobile"
          />
        </view>
      </view>
      <view class="form-item clearfix">
        <view class="form-label">销售区域</view>
        <view class="float_right form-value" @click="showRight = true">
          <text v-if="is_all_region === 5">全国</text>
          <text v-else>部分区域</text>
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </view>
    </form>
    <view class="fixed-bottom"
      ><view class="sub-btn" @click="submitData">保存</view></view
    >
    <view v-if="showRight" class="drawer-view">
      <view class="sel-all-region-view">
        <view
          class="sel-region-li"
          :class="[is_all_region === 5 ? 'sel-region-on' : '']"
          @click="changeSaleRegion(5)"
        >
          <text
            class="ibonfont"
            :class="[
              is_all_region === 5 ? 'ibonxuanze_xuanzhong' : 'ibonxuanze',
            ]"
          ></text>
          <text>全国</text>
        </view>
        <view
          class="sel-region-li"
          :class="[is_all_region === 4 ? 'sel-region-on' : '']"
          @click="changeSaleRegion(4)"
        >
          <text
            class="ibonfont"
            :class="[
              is_all_region === 4 ? 'ibonxuanze_xuanzhong' : 'ibonxuanze',
            ]"
          ></text>
          <text>部分</text>
        </view>
      </view>
      <scroll-view
        v-show="is_all_region === 4"
        :lower-threshold="42"
        class="scroll-type"
        scroll-y
      >
        <!-- regionTree 替换为简单列表或自定义实现 -->
        <view v-for="region in regionList" :key="region.value">
          <label>
            <input type="checkbox" :value="region.value" v-model="SaleRegion" />
            {{ region.label }}
          </label>
        </view>
      </scroll-view>
      <view class="search-bo-btn">
        <view class="sb-btn-li" @click="showRight = false">重置</view>
        <view class="sb-btn-li" @click="searchList">确认</view>
      </view>
    </view>
  </view>
</template>

<script>
import RegionSel from "@/components/region/RegionSel.vue";
import QiniuUpload from "@/components/qiniu/QiniuUpload.vue";
import url from "@/common/config.js";
export default {
  components: {
    RegionSel,
    QiniuUpload,
  },
  data() {
    const validateTime = (rule, value, callback) => {
      if (!value.isAllDay) {
        if (!value.start) {
          callback(new Error("请选择开始时间"));
        } else if (!value.end) {
          callback(new Error("请选择结束时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      const re = /^1[3456789]\d{9}$/; // 正则表达式
      if (value === "") {
        callback(new Error("请输入手机号!"));
      } else if (!re.test(value)) {
        callback(new Error("手机号格式有误，请重新输入!"));
      } else {
        callback();
      }
    };
    const validateRegion = (rule, value, callback) => {
      if (!this.form.salesArea.length) {
        callback(new Error("请选择销售区域"));
      } else {
        callback();
      }
    };
    return {
      region_show: false,
      is_all_region: 5, // 销售区域是否选择全国，默认是
      showTime: false,
      showETime: false,
      SaleRegion: "",
      showRight: false,
      shopTypeList: [
        {
          value: 1,
          label: "联营商铺",
        },
        {
          value: 2,
          label: "直营商铺",
        },
      ],
      cost_algorithm: [
        {
          label: "移动加权法",
          value: 1,
        },
        {
          label: "个别计价法",
          value: 2,
        },
      ],
      linkageDval: [],
      typeName: "",
      costName: "",
      shopTypeName: "",
      regionName: "",
      regionContactname: "",
      showDepartment: false,
      detalutTime: "",
      shopId_id: 0,
      PartnershipSel: "",
      accountNon: "",
      form: {
        logo: "",
        name: "",
        costType: "",
        shopCode: "",
        shopType: "",
        shopPartnerId: "",
        contactName: "",
        partnerName: "",
        salesArea: ["0-0-0"],
        openTime: {
          start: "",
          end: "",
          isAllDay: "",
        },
        mobile: "",
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        address: "",
        latitude: "",
        longitude: "",
      },
      werahouseData: "",
      warehouse_arr: [],
      rules: {
        logo: [
          {
            required: true,
            message: "请上传商铺LOGO",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入商铺名称",
          },
        ],
        shopType: [
          {
            required: true,
            message: "请选择商铺类型",
          },
        ],
        districtCode: [
          {
            required: true,
            message: "请选择商铺地址",
          },
        ],
        model: [
          {
            required: true,
            message: "请选择经营模式",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入详细地址",
          },
        ],
        openTime: [
          {
            required: true,
            validator: validateTime,
          },
        ],
        region: [
          {
            required: true,
            validator: validateRegion,
            trigger: "change",
          },
        ],
      },
      regionList: [
        // 示例数据，实际应根据业务调整
        { value: "0-0-0", label: "全国" },
        { value: "1-1-1", label: "区域1" },
        { value: "2-2-2", label: "区域2" },
      ],
    };
  },
  watch: {
    werahouseData(val) {
      const list = [
        {
          warehouseName: val.warehouseName,
          warehouseId: parseInt(val.id),
          warehouseCode: val.warehouseCode,
        },
      ];
      //   const list = val.map((item) => {
      //     return {
      //       warehouseName: item.warehouseName,
      //       warehouseId: parseInt(item.id),
      //       warehouseCode: item.warehouseCode,
      //     };
      //   });
      if (!this.warehouse_arr.length) {
        this.warehouse_arr = list;
      } else {
        this.warehouse_arr = this.$_util.unique(
          this.warehouse_arr.concat(list),
          ["warehouseId"]
        );
      }
    },
  },
  onShow() {
    // 选择合伙人/合伙企业
    if (this.PartnershipSel) {
      this.form.shopPartnerId = this.PartnershipSel.id;
      this.form.partnerName = this.PartnershipSel.name;
    }
  },
  async onLoad(options) {
    // 表单验证
    this.$nextTick(() => {
      this.$refs.form.setRules(this.rules);
    });

    if (options.id) {
      this.shopId_id = options.id;
      await this.getDetail();
      uni.setNavigationBarTitle({
        title: "编辑商铺",
      });
    }
  },

  methods: {
    changeSaleRegion(val) {
      this.is_all_region = val;
    },
    searchList() {
      this.form.salesArea = this.$refs.regionTree.getCheckedKeys();
      const region = this.$refs.regionTree.getCheckedNodes();
      this.SaleRegion = region[0].label;
      this.showRight = false;
    },
    endTimeChange(e) {
      this.form.openTime.end = e.detail.value;
    },
    startTimeChange(e) {
      this.form.openTime.start = e.detail.value;
    },
    // selDataAu 是否全天
    selDataAu(val) {
      this.form.openTime.isAllDay = val;
    },
    // 选择商铺图片
    uploadSuccess(res) {
      const uploadPicUrl = this.$store.state.getStorage.config.domain+`/${res.key}`;
      this.form.logo = uploadPicUrl;
    },
    shopChange(row) {
      console.log(row);
      this.shopTypeName = row.value ? row.label : "";
      this.form.shopType = row.value;
    },
    pickerTypeChange(row) {
      this.costName = row.value ? row.label : "";
      this.form.costType = row.value;
    },
    chooseWarehouse() {
      this.goPage("/pagesT/werahouse/selWerahouse");
    },
    delWarehouse(index) {
      console.log(index);
      this.warehouse_arr.splice(index, 1);
    },
    // 选择详细地址
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.form.latitude = res.latitude;
          this.form.longitude = res.longitude;
          this.form.address = res.address;
        },
      });
    },
    // 商铺地址
    regionConfirm(val) {
      this.form.provinceCode = val[0].value;
      this.form.cityCode = val[1].value;
      this.form.districtCode = val[2].value;
      this.regionName = [val[0].label, val[1].label, val[2].label].join("-");
    },
    regionCancel() {
      this.region_show = false;
    },
    regionOpen() {
      this.region_show = true;
    },
    switchChange(e) {
      this.form.openTime.isAllDay = e.detail.value ? 1 : "";
    },
    // 获取详情
    async getDetail() {
      const {
        err,
        data: { data },
      } = await this.$u.api.getShopInfo(this.shopId_id);
      if (err) return;
      this.form = data;
      //  将字符串转为数组
      this.regionName = [
        data.area.provinceName,
        data.area.cityName,
        data.area.districtName,
      ].join("-");
      if (JSON.stringify(data.salesArea) === '["0-0-0"]') {
        this.is_all_region = 5;
      } else {
        this.is_all_region = 4;
      }
      this.SaleRegion = data.salesArea;
      this.shopTypeName = this.shopTypeList.find((item) => {
        return (item.value = data.shopType);
      }).label;
      this.costName = this.cost_algorithm.find((item) => {
        return (item.value = data.costType);
      }).label;
      let warehouseData = [];
      for (let i in data.warehouseData) {
        warehouseData.push({
          ...data.warehouseData[i],
          warehouseId: parseInt(data.warehouseData[i].warehouseId),
        });
      }
      this.warehouse_arr = warehouseData;
    },
    // 提交
    async submitData() {
      //   this.$refs.form.validate(async (res) => {
      // if (res) {
      let target = {};
      let salesArea =
        this.is_all_region === 5 ? ["0-0-0"] : this.form.salesArea;
      const warehouseId = this.warehouse_arr.map((item) => {
        return item.warehouseId;
      });
      if (this.shopId_id) {
        target = await this.$u.api.editShop(this.shopId_id, {
          ...this.form,
          salesArea: salesArea,
          warehouseId: warehouseId,
        });
      } else {
        target = await this.$u.api.addShop({
          ...this.form,
          salesArea: salesArea,
          warehouseId: warehouseId,
        });
      }
      uni.showLoading();
      const { err, data } = target;
      uni.hideLoading();
      if (err) return;
      this.$u.toast("提交成功");
      uni.navigateBack();
      //   this.goPage("/pagesA/systemSet/ShopList", "redirectTo");
      //     }
      //   });
    },
    // 新增picker回调
    shopChangePicker(e) {
      const idx = e.detail.value;
      const row = this.shopTypeList[idx];
      this.shopTypeName = row.label;
      this.form.shopType = row.value;
    },
  },
};
</script>

<style lang="scss">
$main-color: #fb5904;
$bg-color: #ffffff;

.form-view {
  background: $bg-color;
  padding: 24rpx 32rpx 120rpx 32rpx;
  min-height: 100vh;
}

.form-item {
  margin-bottom: 32rpx;
  background: $bg-color;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(251, 89, 4, 0.04);
  padding: 10px;
  .form-label {
    color: #333;
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 12rpx;
    display: flex;
    align-items: center;
    .icon-requird {
      color: $main-color;
      margin-left: 8rpx;
      font-size: 24rpx;
    }
  }
  .form-value {
    display: flex;
    align-items: center;
    background: #ffffff;
    border-radius: 12rpx;
    padding: 0 24rpx;
    min-height: 88rpx;
    font-size: 30rpx;
    color: #333;
    width: 100%;
    .form-input {
      flex: 1;
      background: transparent;
      border: none;
      outline: none;
      font-size: 30rpx;
      color: #333;
      padding: 24rpx 0;
      &::placeholder {
        color: #bbb;
      }
    }
    .input-pl {
      color: #bbb;
      font-size: 30rpx;
    }
    .ibonjinru {
      color: $main-color;
      font-size: 32rpx;
      margin-left: 16rpx;
    }
  }
}

.sel-label,
.sel-name {
  color: #333;
  font-size: 30rpx;
}
.input-pl {
  color: #bbb;
  font-size: 30rpx;
}

.TimeBorder {
  min-width: 120rpx;
  padding: 12rpx 24rpx;
  border: 1rpx solid $main-color;
  border-radius: 8rpx;
  color: $main-color;
  font-size: 30rpx;
  background: $bg-color;
  text-align: center;
}

.line {
  width: 32rpx;
  text-align: center;
  color: #bbb;
  font-size: 32rpx;
  margin: 0 8rpx;
}

.form-up {
  background: $bg-color;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(251, 89, 4, 0.04);
  padding: 0 24rpx;
  .form-label {
    color: #333;
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 12rpx;
    .icon-requird {
      color: $main-color;
      margin-left: 8rpx;
      font-size: 24rpx;
    }
  }
  .form-value {
    display: flex;
    align-items: center;
    gap: 16rpx;
    width: 100%;
  }
}

.upload-view {
  width: 144rpx;
  height: 144rpx;
  background: #f8f8f8;
  border: 2rpx dashed $main-color;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: $main-color;
  font-size: 60rpx;
  .ibonxinzeng {
    font-size: 60rpx;
  }
}

.cata-img {
  width: 144rpx;
  height: 144rpx;
  border-radius: 16rpx;
  margin-right: 16rpx;
  object-fit: cover;
  border: 2rpx solid $main-color;
}

.tag-item {
  display: inline-flex;
  align-items: center;
  //   background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 4px;
  margin-right: 6px;
  font-size: 26rpx;
  color: #ffffff !important;
  background-color: #fb5904 !important;
  button {
    margin-left: 4px;
    font-size: 24rpx;
    padding: 0 8rpx;
    height: 40rpx;
    line-height: 40rpx;
    border-radius: 8rpx;
  }
}

.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: $bg-color;
  box-shadow: 0 -2rpx 16rpx rgba(0, 0, 0, 0.04);
  padding: 24rpx 32rpx;
  z-index: 10;
  .sub-btn {
    width: 100%;
    background: $main-color;
    color: $bg-color;
    font-size: 34rpx;
    border-radius: 12rpx;
    text-align: center;
    padding: 24rpx 0;
    font-weight: 600;
    letter-spacing: 2rpx;
    box-shadow: 0 4rpx 16rpx rgba(251, 89, 4, 0.08);
    transition: background 0.2s;
    &:active {
      background: darken($main-color, 8%);
    }
  }
}

.dataAu-ul {
  display: flex;
  .dataAu-li {
    text-align: center;
    flex: 3;
    .ibonfont {
      margin-right: 10upx;
      font-size: 32upx;
      color: #666;
    }
    .ibonxuanze_xuanzhong {
      color: $main-color;
    }
  }
}

.dis-time {
  background-color: #eee;
  color: #999;
}

.sel-all-region-view {
  display: flex;
  text-align: center;
  border-bottom: 1px solid #eee;
  border-top: 1px solid #eee;
  padding: 20upx 0;
  background-color: #fff;
  .sel-region-li {
    flex: 2;
    font-size: 26upx;
    border-right: 1px solid #eee;
    .ibonfont {
      color: #999;
      margin-right: 10upx;
      font-size: 32upx;
      vertical-align: middle;
    }
  }
  .sel-region-on {
    color: $main-color;
    .ibonfont {
      color: $main-color;
    }
  }
}
.scroll-type {
  height: calc(100vh - 180upx);
}

.drawer-view {
  .search-bo-btn {
    box-shadow: 0px -4upx 10upx 0upx rgba(0, 0, 0, 0.06);
    position: absolute;
    z-index: 9;
    bottom: 0;
    left: 0;
    display: flex;
    padding: 10upx;
    width: calc(100% - 20upx);

    .sb-btn-li:first-child {
      margin-right: 10upx;
    }

    .sb-btn-li {
      flex: 2;
      height: 66upx;
      line-height: 66upx;
      text-align: center;
      color: #666;
      border: 1upx solid #eee;
      border-radius: 4upx;
      background: #fff;
    }

    .sb-btn-li:last-child {
      color: #fff;
      border-color: #fb5904;
    }
  }
}

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

.float_left {
  float: left;
}
</style>
